<template>
  <div>
    <el-dialog
      :title="title"
      :modelValue="visible"
      @update:modelValue="emit('update:visible', $event)"
      width="900px"
      append-to-body
      class="seal-dialog"
    >
      <template #default>
        <div style="padding-right: 24px;">
          <el-form ref="sealFormRef" :model="form" :rules="rules" label-width="140px" label-position="left" style="padding: 20px 0 20px 24px">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="编号" prop="number">
                  <el-input v-model="form.number" placeholder="请输入编号" :readonly="true" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="申请人" prop="presidentsName">
                  <el-input v-model="form.presidentsName" placeholder="请输入编号" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="申请部门" prop="deptName">
                  <el-tree-select
                    v-model="form.deptName"
                    :data="deptTree"
                    placeholder="请选择申请部门"
                    :props="{ label: 'label', value: 'id', children: 'children' }"
                    check-strictly
                    filterable
                    :default-expand-all="true"
                    style="width: 100%"
                    @visible-change="handleVisibleChange"
                    @change="handleDeptChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
              <el-form-item label="项目名称" prop="projectIdArray">
                <el-select
                  v-model="form.projectIdArray"
                  multiple
                  placeholder="请输入项目名称搜索"
                  clearable
                  filterable
                  remote
                  reserve-keyword
                  :remote-method="searchProjects"
                  :loading="projectLoading"
                  style="width: 100%"
                  @change="handleProjectChange"
                >
                  <el-option
                    v-for="project in projectList"
                    :key="project.id"
                    :label="`${project.proName} (${project.proNumber || ''})`"
                    :value="String(project.id)"
                  />
                  <template #empty>
                    <div class="text-center p-2">
                      <span v-if="projectLoading">加载中...</span>
                      <span v-else-if="projectSearchKeyword && projectList.length === 0">未找到相关项目</span>
                      <span v-else>请输入项目名称进行搜索</span>
                    </div>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
              <el-col :span="24">
                <el-form-item label="印章类型" prop="sealType">
                  <el-select
                    v-model="sealTypeArray"
                    placeholder="请选择印章类型"
                    multiple
                    allow-create
                    style="width: 100%;"
                    :filterable="false"
                    @change="onSelectChange"
                  >
                    <el-option
                      v-for="item in sealTypeOptions"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <!-- 其它输入框 + 按钮 -->
                <el-form-item
                  v-if="openOtherInput"
                  label="其它印章"
                  style="display: flex; align-items: center; width: 100%;"
                >
                  <el-input
                    v-model="otherSealType"
                    placeholder="请输入其它印章类型"
                    clearable
                    style="flex: 1; margin-right: 8px;"
                    @keyup.enter="addOtherSealType"
                  />
                  <el-button type="primary" @click="addOtherSealType" style="width: 100px;">
                    确定
                  </el-button>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="用章事由" prop="sealCause">
                  <el-input v-model="form.sealCause" placeholder="请输入用章事由" type="textarea" :rows="4" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="印章文件" prop="sealFiles" style="width: 100%">
                  <div style="display: flex; gap: 8px; width: 100%">
                    <el-input v-model="sealFileInput.fileName" placeholder="请输入文件名"/>
                    <el-input-number v-model="sealFileInput.fileCount" :min="1" placeholder="份数"/>
                    <el-button type="primary" @click="addSealFile" :disabled="!sealFileInput.fileName || !sealFileInput.fileCount">确定</el-button>
                  </div>
                </el-form-item>
                <el-form-item v-if="sealFiles.length > 0">
                  <el-tag
                    v-for="(file, idx) in sealFiles"
                    :key="file.fileName + idx"
                    closable
                    @close="removeSealFile(idx)"
                    style="margin-right: 8px; margin-bottom: 4px"
                  >
                    {{ file.fileName }}（{{ file.fileCount }}份）
                  </el-tag>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="使用日期" prop="useDate">
                  <el-date-picker clearable v-model="form.useDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择使用日期" style="width: 100%" :editable="false"> </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="使用类型" prop="useType">
                  <el-select v-model="form.useType"  :empty-values="[null, undefined]" placeholder="请选择使用类型" style="width: 100%">
                    <el-option
                      v-for="item in seal_use_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :rows="3" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

        <!-- 审核流程配置对话框 --> 
    <ApprovalFlow v-model:visible="approvalFlowVisible" :business-type="'ADM-SEAL-AUDIT'"
      :business-id="auditIdForApproval" :key="auditIdForApproval" title="配置印章申请审核流程" @confirm="handleApprovalConfirm"
      @cancel="handleApprovalCancel" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, computed, onMounted, watch } from 'vue';
import { getCurrentInstance } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import { addSeal, updateSeal, getSealNumber, getSeal, getDeptTree } from '@/api/general/administration/seal';
import type { SealForm, SealFile, DeptTreeNode } from '@/api/general/administration/seal/types';
import { getSuperior } from '@/api/system/user';
import type { UserVO } from '@/api/system/user/types';
import { pageListForQuery, getProInfo } from '@/api/project/init/proInfo';
import { useUserStore } from '@/store/modules/user';
import type { FormInstance, FormRules } from 'element-plus';
import type { ProInfoVO } from '@/api/project/init/proInfo/types';
import { resetApprovalStatus } from '@/components/ApprovalFlow/api';
import { listProContract } from '@/api/project/init/contract';
import { getProjectNamesByIds, pageListProInfo } from '@/api/project/init/proInfo';
import { ItemTreeNode } from '@/api/project/init/contract/types';

const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  visible: {
    type: Boolean,
    default: false
  }
});


const emit = defineEmits(['update:visible', 'success']);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { seal_status, seal_use_type } = toRefs<any>(proxy?.useDict('seal_status', 'seal_use_type'));

const buttonLoading = ref(false);
const sealFormRef = ref<FormInstance>();
// 标记是否已经加载过
const treeLoaded = ref(false);

// 印章类型初始化
const sealTypeOptions = ['公章', '财务章', '法人章', '测绘资质章', '其它'] as const;
const otherSealType = ref('');
// 新增本地变量 sealTypeArray
const sealTypeArray = ref<string[]>([]);
// 内部用于 select 显示的数组（包含“其它”触发输入框）
const internalSelect = ref<string[]>([]);
// 判断是否显示“其它”输入框
const openOtherInput = ref(false);

// 初始化项目下拉框
const projectTree = ref<ItemTreeNode[]>([]);

// 用户信息
const userStore = useUserStore();

const projectList = ref<ProInfoVO[]>([]);

// 搜索关键词
const projectSearchKeyword = ref('');
const flowSearchKeyword = ref('');
const projectLoading = ref(false);
const flowLoading = ref(false);

// 提交审核相关
const approvalFlowVisible = ref(false);
const currentSubmitAuditRow = ref<any>(null);
const auditIdForApproval = ref<string | number | undefined>(undefined);
// 防止并发请求覆盖
let currentRequestId = 0;
// 防抖计时器
let projectSearchTimer: NodeJS.Timeout | null = null;
// 定义需要触发必填校验的部门名称或 ID
const requiredProjectDepts = ["董办", "综合办", "财务中心","商务中心"];
// 回显状态，防止重复调用
const backfillDone = ref(false);

// 判断是否为新增
const isAdd = computed(() => !form.value.id);

const initFormData: SealForm = {
  id: undefined,
  number: undefined,
  projectIdArray: [] as string[],
  proId: undefined,
  useDate: undefined,
  useType: undefined,
  sealType: undefined,
  sealCause: undefined,
  status: '0', // 默认未审批
  approverIdea: undefined,
  sealFiles: [],
  presidentsName: userStore.name,
  deptId: userStore.deptId,
  deptName: userStore.deptName,
};

const form = ref<SealForm>({ ...initFormData });
const rules = reactive<FormRules>({
  number: [{ required: true, message: '请输入编号', trigger: 'blur' }],
  presidentsName: [{ required: true, message: '请输入申请人名称', trigger: 'blur' }],
  deptName: [{ required: true, message: '请选择申请部门', trigger: 'change' }],
  // 项目id
  projectIdArray: [
    { required: true, message: '请选择项目', trigger: 'change' }
  ],
  sealFiles: [
    {
      validator: (rule, value, callback) => {
        if (!sealFiles.value.length) {
          callback(new Error('请至少添加一个印章文件'));
        } else {
          callback();
        }
      },
      trigger: 'change',
      required: true,
      message: '请至少添加一个印章文件'
    }
  ],
  useDate: [{ required: true, message: '请选择使用日期', trigger: 'change' }],
  useType: [{ required: true, message: '请选择使用类型', trigger: 'change' }],
  sealType: [
    {
      validator: (rule, value, callback) => {
        if (!sealTypeArray.value.length) {
          callback(new Error('请选择印章类型'));
        } else {
          callback();
        }
      },
      trigger: 'change',
      required: true,
      message: '请选择印章类型'
    }
  ],
  sealCause: [{ required: true, message: '请输入用章事由', trigger: 'blur' }]
});

// 部门树初始化
const deptTree = ref<DeptTreeNode[]>([]);
const deptTreeSelectRef = ref();

// 获取部门树
const fetchDeptTree = async () => {
  try {
    const res = await getDeptTree();
    const processNode = (node: any) => {
      if (node.children && node.children.length > 0) {
        // 有子节点 → 禁用，但允许展开
        node.disabled = true;
        node.children.forEach(processNode); // 递归处理子节点
      } else {
        // 叶子节点 → 可选
        node.disabled = false;
      }
    };
    if (Array.isArray(res.data)) {
      res.data.forEach(processNode);
    }
    deptTree.value = res.data;
  } catch (error) {
    console.error('获取部门树失败:', error);
    proxy?.$modal.msgError('获取部门树失败');
  }
};


// 下拉框打开时展开全部节点
const handleVisibleChange = (visible: boolean) => {
  console.log('handleVisibleChange', visible);
  if (visible) {
    // 展开全部节点（treeSelect 内部的 tree 是 el-tree 实例）
    setTimeout(() => {
      const tree = deptTreeSelectRef.value?.$refs?.tree;
       tree?.expandAll?.();
    }, 0);
  }
};

// 绑定印章类型下拉框处理'其它'选择的逻辑
const onSelectChange = (val: string[]) => {
  // 如果选了“其它”，打开输入框
  openOtherInput.value = val.includes('其它');
  // 保留 “其它” 用于触发 UI
  if (!val.includes('其它')) val.push('其它');
  // 更新最终提交数据，不包含 “其它”
  sealTypeArray.value = val.filter(item => item !== '其它');
};

// 点击按钮添加自定义印章
const addOtherSealType = () => {
  const value = otherSealType.value.trim();
  if (value && !sealTypeArray.value.includes(value)) {
    // 添加到最终数据
    sealTypeArray.value.push(value);
    // 自动加入 select 显示
    if (!internalSelect.value.includes(value)) {
      internalSelect.value.push(value);
    }
    // 清空输入框
    otherSealType.value = '';
  }
  // 点击确定后关闭输入框
  openOtherInput.value = false;
  // 保持 select 中有“其它”
  if (!internalSelect.value.includes('其它')) {
    internalSelect.value.push('其它');
  }
};


const superiorOptions = ref<UserVO[]>([]);

// 获取上级用户列表
const fetchSuperiorList = async () => {
  try {
    const res = await getSuperior();
    superiorOptions.value = res.data;
  } catch (error) {
    console.error('获取上级用户列表失败:', error);
    proxy?.$modal.msgError('获取上级用户列表失败');
  }
};

// 通过项目id获取项目信息回显
const getProjectInfo = async (projectId: string | number) => {
  try {
    const res = await getProInfo(projectId);
    if (res.data) {
      // 清空并只保留当前项目（适合只需要一个选项的情况）
      projectList.value = [{
        id: res.data.id,
        contractId: res.data.contractId,
        proName: res.data.proName,
        proNumber: res.data.proNumber,
        proType: res.data.proType,
        proContent: res.data.proContent,
        proPresidentsId: res.data.proPresidentsId,
        proPresidentsName: res.data.proPresidentsName,
        proLeadersId: res.data.proLeadersId,
        proAmount: res.data.proAmount,
        proAmountRemark: res.data.proAmountRemark,
        remark: res.data.remark,
        proStatus: res.data.proStatus,
      }];
    }
  } catch (error) {
    console.error('通过项目id获取项目信息回显失败:', error);
    proxy?.$modal.msgError('通过项目id获取项目信息回显失败');
  }
};


// 部门选择处理（安全版）
const handleDeptChange = (selectedId: string | number) => {
  console.log('[handleDeptChange] 选中部门 ID:', selectedId);
  const selectedNode = findNodeById(deptTree.value, selectedId);
  if (!selectedNode) return;

  console.log('[handleDeptChange] 选中部门名称:', selectedNode.label);

  if (requiredProjectDepts.includes(selectedNode.label)) {
    console.log('[handleDeptChange] 部门在必填列表，触发项目搜索');
    searchProjects(selectedNode.label, true); // 传 true
  } else {
    console.log('[handleDeptChange] 部门不在必填列表，清空项目选择');
    form.value.projectIdArray = []; // 清空多选回显
    projectList.value = [];         // 可选：清空下拉列表
  }
};

// 遍历树查找节点
function findNodeById(tree: any[], id: string | number): any {
  for (const node of tree) {
    if (node.id === id) return node;
    if (node.children) {
      const found = findNodeById(node.children, id);
      if (found) return found;
    }
  }
  return null;
}

/** 远程搜索项目 */
const searchProjects = (query: string, isDeptTrigger = false) => {
  projectSearchKeyword.value = query;
  if (projectSearchTimer) clearTimeout(projectSearchTimer);

  projectSearchTimer = setTimeout(() => {
    getProjectList(query || '', isDeptTrigger);
  }, 300);
};

// 获取项目列表
const getProjectList = async (searchKeyword = '', isDeptTrigger = false) => {
  try {
    projectLoading.value = true;
    const requestId = ++currentRequestId;

    const res = await pageListForQuery({
      pageNum: 1,
      pageSize: 50,
      flowStatus: '3',
      proName: searchKeyword || undefined
    });

    if (requestId !== currentRequestId) return; // 避免旧请求覆盖

    projectList.value = res.rows || [];
    console.log('[getProjectList] 接口返回项目列表数量:', projectList.value.length);

    if (isDeptTrigger) {
      // 部门触发搜索 → 全部项目 ID 回显
      form.value.projectIdArray = projectList.value.map(p => String(p.id));
      console.log('[回显] 部门触发 projectIdArray:', form.value.projectIdArray);
    } else if (!backfillDone.value && form.value.projectIdArray?.length) {
      // 回显逻辑：检查本地是否匹配全部 ID
      const missingIds = form.value.projectIdArray.filter(
        id => !projectList.value.some(p => String(p.id) === id)
      );

      if (missingIds.length > 0) {
        console.log('[getProjectList] 有缺失项目，需要调用搜索补全:', missingIds);
        backfillDone.value = true; // 标记已经补全，避免循环

        // 调用远程接口补全
        const projectPromises = missingIds.map(id => getProInfo(Number(id)));
        const projectData = await Promise.all(projectPromises);

        // 将补全的数据加入项目列表并更新回显
        projectData.forEach(res => {
          if (res?.data) {
            projectList.value.push({
              id: res.data.id,
              proName: res.data.proName,
              proNumber: res.data.proNumber,
              contractId: 0,
              contractName: '',
              projectRegion: '',
              proType: '',
              proContent: '',
              proPresidentsId: '',
              proLeadersId: '',
              ownerUnit: '',
              proAmount:  null,
              proAmountRemark: '',
              proStatus: '',
              remark: '',
              createTime: '',
              createBy: ''
            });
          }
        });

        // 确保回显
        form.value.projectIdArray = [...form.value.projectIdArray];
        console.log('[getProjectList] 补全完成，停止回显循环');
      } else {
        console.log('[getProjectList] 本地列表匹配到全部 projectId，回显完成');
        backfillDone.value = true;
      }
    }
  } catch (error) {
    console.error('获取项目列表失败:', error);
    ElMessage.error('获取项目列表失败');
  } finally {
    projectLoading.value = false;
  }
};

/** 处理项目选择变化 */
const handleProjectChange = (value: number | string | undefined) => {
  flowSearchKeyword.value = ''; // 清空流程搜索关键词

  // 项目改变时不清空工作日志列表，允许多个项目的数据共存
};

onMounted(() => {
  fetchDeptTree();
  fetchSuperiorList();
});

/** 获取编号 */
const getNumber = async () => {
  try {
    const res = await getSealNumber();
    if (res.data) {
      form.value.number = res.data;
      // 强制更新表单数据
      sealFormRef.value?.validateField('number');
    }
  } catch (error) {
    console.error('获取编号失败:', error);
    proxy?.$modal.msgError('获取编号失败');
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  emit('update:visible', false);
};

/** 表单重置 */
const reset = async () => {
  Object.assign(form.value, initFormData);
  sealFormRef.value?.resetFields();
  if (form.value.deptId) {
    handleDeptChange(form.value.deptId);
  }
  sealTypeArray.value = [];
  principalIdsArray.value = [];
  sealFiles.value = [];
  form.value.useDate = undefined;
  form.value.useType = undefined;
  form.value.sealCause = undefined;
  form.value.deptId = undefined;
  // 如果是新增，获取编号
  if (!form.value.id) {
    await getNumber();
  }
};

const upload = reactive({
  url: import.meta.env.VITE_APP_BASE_API + '/common/upload',
  headers: { Authorization: 'Bearer ' + useUserStore().token },
  fileList: [] as any[]
});

const sealFileInput = reactive({ fileName: '', fileCount: 1 });
const sealFiles = ref<SealFile[]>([]);

const addSealFile = () => {
  if (sealFileInput.fileName && sealFileInput.fileCount) {
    sealFiles.value.push({ fileName: sealFileInput.fileName, fileCount: sealFileInput.fileCount });
    sealFileInput.fileName = '';
    sealFileInput.fileCount = 1;
  }
};

const removeSealFile = (idx: number) => {
  sealFiles.value.splice(idx, 1);
};


// 添加principalIdsArray响应式变量
const principalIdsArray = ref<(string | number)[]>([]);

/** 提交按钮 */
const submitForm = () => {
  sealFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        form.value.sealType = sealTypeArray.value.join(',');
        form.value.principalIds = principalIdsArray.value.join(',');
        const submitData = { ...form.value, sealFiles: sealFiles.value };
        if (form.value.id) {
          await updateSeal(submitData);
          // 调用重置审核流程接口
          await resetApprovalStatus('ADM-SEAL-AUDIT', Number(form.value.id), '不可审核')
        } else {
          const res = await addSeal(submitData);
          // 触发审核流程配置对话框
          auditIdForApproval.value = res.data;
          approvalFlowVisible.value = true;
        }
        proxy?.$modal.msgSuccess('操作成功');
        emit('update:visible', false);
        emit('success');
      } catch (error) {
        console.error('提交失败:', error);
        proxy?.$modal.msgError('操作失败');
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

// 监听对话框关闭
watch(approvalFlowVisible, async (newVal, oldVal) => {
  if (oldVal && !newVal) {
    // 对话框从显示变成隐藏时刷新列表
    emit('success');
  }
});

/**
 * 检查是否需要触发 handleDeptChange 或补全项目数据
 * 触发条件：
 *   1. 部门存在
 *   2. 项目为空 → 调用 handleDeptChange
 *   3. 项目不为空 → 调用补全逻辑
 */
async function tryHandleDeptChange() {
  const deptId = form.value.deptId;
  const projectId = form.value.proId;
  const isProjectEmpty =
    projectId === undefined ||
    projectId === null ||
    projectId === '' ||
    (Array.isArray(projectId) && projectId.length === 0);

  console.log('[tryHandleDeptChange] deptId:', deptId, 'projectId:', projectId, 'isProjectEmpty:', isProjectEmpty);

  if (deptId && isProjectEmpty) {
    console.log('[tryHandleDeptChange] 条件满足 → 触发 handleDeptChange');
    handleDeptChange(deptId);
  } else if (projectId) {
    console.log('[tryHandleDeptChange] 项目已存在 → 开始补全项目信息');
    await backfillProjectList(projectId);
  } else {
    console.log('[tryHandleDeptChange] 条件不满足 → 不执行任何操作');
  }
}

/**
 * 补全项目数据，仅用于已有 projectId 时的回显
 */
async function backfillProjectList(projectId: string | string[]) {
  try {
    backfillDone.value = true; // 防止重复调用
    // 转换成数组（支持字符串或数组）
    const ids = Array.isArray(projectId)
      ? projectId
      : projectId.split(',').map(id => id.trim()).filter(Boolean);

    console.log('[backfillProjectList] 待补全项目 ID 列表:', ids);
    const projectPromises = ids.map(id => getProInfo(Number(id)));
    const projectData = await Promise.all(projectPromises);
    projectData.forEach(res => {
      if (res?.data) {
        projectList.value.push({
          id: res.data.id,
          proName: res.data.proName,
          proNumber: res.data.proNumber,
          contractId: 0,
          contractName: '',
          projectRegion: '',
          proType: '',
          proContent: '',
          proPresidentsId: '',
          proLeadersId: '',
          ownerUnit: '',
          proAmount: null,
          proAmountRemark: '',
          proStatus: '',
          remark: '',
          createTime: '',
          createBy: ''
        });
      }
    });
    // ✅ 更新回显，不触发部门逻辑
    form.value.projectIdArray = ids.map(String);
    console.log('[backfillProjectList] 项目补全完成，projectIdArray:', form.value.projectIdArray);
  } catch (error) {
    console.error('[backfillProjectList] 项目补全失败:', error);
  }
}

const openDialog = async (data?: SealForm) => {
  if (data) {
    Object.assign(form.value, data);
    tryHandleDeptChange();
    sealTypeArray.value = data.sealType ? data.sealType.split(',') : [];
    // 等待上级用户列表加载完成
    if (superiorOptions.value.length === 0) {
      await fetchSuperiorList();
    }
    principalIdsArray.value = data.principalIds ? data.principalIds.split(',').map((id) => String(id)) : [];
    sealFiles.value = Array.isArray((data as any).sealFiles)
      ? (data as any).sealFiles.map((f: any) => ({
          fileName: f.fileName,
          fileCount: f.fileCount
        }))
      : [];
  } else {
    await reset();
  }
};

/** 审核流程确认回调 */
const handleApprovalConfirm = async () => {
  try {
    ElMessage.success('工作日志审核流程提交成功');
    approvalFlowVisible.value = false;
    currentSubmitAuditRow.value = null;
    auditIdForApproval.value = undefined;
  } catch (error) {
    console.error('审核流程提交失败:', error);
    ElMessage.error('审核流程提交失败');
  }
};

/** 审核流程取消回调 */
const handleApprovalCancel = () => {
  approvalFlowVisible.value = false;
  currentSubmitAuditRow.value = null;
  auditIdForApproval.value = undefined;
  // 审核流程取消时，表单已经在submitCurrentWorklogs中重置了，这里不需要重复重置
};



defineExpose({
  form,
  reset,
  openDialog
});



</script>

<style scoped>
.seal-dialog :deep(.el-dialog__header) {
  text-align: center;
}

/* 合同对话框中的用户选择器样式 */
.user-selector-container {
  width: 100%;
}

.user-selector-container .selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
  min-height: 20px;
}

/* 对话框样式优化 */
:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
}


</style>
